package cn.ihna.demo.client.http;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;

import java.net.URI;
import java.nio.charset.StandardCharsets;

/**
 * @author xianyingda@gmail.com
 * @serial
 * @since 2020-08-16 13:00
 */
public class NettyHttpClient {
    public static void main(String[] args) throws Exception {
        EventLoopGroup eventExecutors = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(eventExecutors);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast(new HttpClientCodec());
                pipeline.addLast(new HttpObjectAggregator(512 * 1024));
                pipeline.addLast(new HttpClientInboundHandler());
            }
        });
        String host = "www.ihna.cn";
        ChannelFuture f = b.connect(host, 80).sync();
        URI uri = new URI("/dev");
        String message = "hello";
        DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
                HttpMethod.GET, uri.toASCIIString(),
                Unpooled.wrappedBuffer(message.getBytes(StandardCharsets.UTF_8)));
        request.headers().set(HttpHeaderNames.HOST, host);
        request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        request.headers().set(HttpHeaderNames.CONTENT_LENGTH, (request).content().readableBytes());
        f.channel().writeAndFlush(request);
        f.channel().closeFuture().sync();

        eventExecutors.shutdownGracefully();
    }
}
